import { app, BrowserWindow, ipcMain } from 'electron'
import { Socket } from 'socket.io'
import { createBrowserWindow, CreateBrowserWindowType } from './createBrowserWindow'
import { initSocket } from './socket'

const getBrowserWindow = (id: number): BrowserWindow => {
  return BrowserWindow.fromId(id)!
}

export const initIpcMain = (): void => {
  let SocketServer: Socket | null

  ipcMain.on('onAppQuit', (event): void => {
    const windiw = getBrowserWindow(event.sender.id)
    windiw.destroy()
  })

  ipcMain.on('onMaximize', (event) => {
    const windiw = getBrowserWindow(event.sender.id)
    const isMax = windiw.isMaximized()
    if (isMax) return windiw.restore()
    windiw.maximize()
  })

  ipcMain.on('onMinimize', (event) => {
    const windiw = getBrowserWindow(event.sender.id)
    const isMin = windiw.isMinimized()
    if (isMin) return windiw.restore()
    windiw.minimize()
  })

  ipcMain.on('showHomeWindow', (event) => {
    const windiw = getBrowserWindow(event.sender.id)
    windiw.hide()
    createBrowserWindow({
      url: '#/home/message',
      options: {
        width: 800,
        height: 600,
        minWidth: 700,
        minHeight: 500,
        center: true,
        title: '主页',
        resizable: true
      }
    }).addListener('closed', () => {
      app.quit()
    })
    windiw.destroy()
  })

  ipcMain.on('createWindow', async (_event, options: CreateBrowserWindowType) => {
    const winlList = BrowserWindow.getAllWindows()
    const win = winlList.find((item): BrowserWindow | undefined => {
      const url = item.webContents.getURL()
      const router = url.substring(url.length - options.url.length, url.length)
      if (router == options.url) return item
      return
    })
    if (win) return win.show()
    createBrowserWindow(options)
  })

  ipcMain.on('initSocket', (event, userId) => {
    SocketServer = initSocket()
    if (SocketServer == null) return
    SocketServer.on('connect', () => {
      SocketServer!.emit('init', { userId: userId })

      SocketServer!.once('getMessageUserList', (data) => {
        event.reply('messageUserList', data)
      })

      SocketServer!.on('newUser', (data) => {
        event.reply('getNewUser', data)
      })

      SocketServer!.on('sendNewMessage', (friend: unknown, message: unknown) => {
        event.reply('getNewMessage', { friend, message })
      })

      SocketServer!.once('getUserApprove', (data) => {
        event.reply('getUserApproveList', data)
      })

      SocketServer!.once('newUserApprove', (data) => {
        event.reply('getNewUserApprove', data)
      })
    })
  })
}
